// pages/tools/swiss-calc/swiss-calc.page.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    total: 128,
    round: 7,
    result: [] as number[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wx.setNavigationBarTitle({
      title: '出轮计算'
    });
    const result = this.calc(this.data.total, this.data.round);
    this.setData({
      result
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  totalChange(e: any) {
    console.log(e)
    let total = this.data.total;
    if (!isNaN(+e.detail.value) && +e.detail.value > 0) {
      total = +e.detail.value;
    }
    const round = Math.ceil(Math.log2(total));
    const result = this.calc(total, round);

    this.setData({
      total,
      round,
      result
    })
  },

  roundChange(e: any) {
    console.log(e)
    let round = Math.ceil(Math.log2(this.data.total));
    if (!isNaN(+e.detail.value) && +e.detail.value > 0) {
      round = +e.detail.value;
    }
    const result = this.calc(this.data.total, round);

    this.setData({
      round,
      result
    })
  },

  calc(total: number, round: number): number[] {
    const result = Array.from({ length: round + 1 }, () => 0);
    result[0] = total;
    let cur = 0;
    do {
      cur++;
      let tmp = 0;
      for (let i = 0; i < cur + 1; i++) {
        const t = result[i];
        const w = Math.ceil(t / 2);
        result[i] = tmp + w;
        tmp = t - w;
      }
    } while (cur < round);
    return result;
  }
})